package com.yonyou.pmclouds.filepreview.controller;

import com.yonyou.pmclouds.basecom.conf.USpaceProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.HttpTookit;
import com.yonyou.pmclouds.basecom.util.StorageFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件预览接口
 *
 * @author yzx
 * @Date: 2018/6/27 15:30
 */
@RestController
@RequestMapping("/file")
public class FilePreviewController {
    @Autowired
    private USpaceProperties uspaceProperties;
    @Autowired
    private StorageFactory storageFactory;

    @RequestMapping("/preview")
    public Object preview(@RequestParam String ossName, HttpServletRequest request) throws BusinessException {
        // 通过阿里云文件名字获取文件的网络地址
        String fileRulePath = storageFactory.getStorageUtil().signUrlForSingleAppPic(ossName, null, request);
        long fileContentLength = storageFactory.getStorageUtil().getFileContentLength(ossName);
        // 友空间需要fileRulePath是encode格式
        String encodeUrl;
        try {
            encodeUrl = URLEncoder.encode(fileRulePath, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("预览地址转码失败!");
        }
        Map<String, String> param = new HashMap<>();
        param.put("fileRulePath", encodeUrl);
        param.put("fileContentLength", Long.toString(fileContentLength));
        // 根据获取到的文件地址请求公有云服务（友空间不让专属云直接访问）
        String pmcloudsForwardPreviewUrl = uspaceProperties.getFileview().getPmcloudsHost()+"/rest/filePreview/forwardPreview";
        return HttpTookit.doGet(pmcloudsForwardPreviewUrl, param);
    }
    /**
     * 通过文件名存储路径，供前端下载使用
     * Notes:
     * 1). Capable for oss and ncc
     * 2). Similar functionality provided at /mobile/oss/signForAppPic
     * @param ossName
     * @return java.lang.String
     * @author yzx
     * @date 2018/7/2 14:19
     */
    @RequestMapping("/download")
    public String download(@RequestParam String ossName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        return storageFactory.getStorageUtil().signUrlForSingleAppPic(ossName, null, request);
    }
}
